package com.aube.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.ToggleButton;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.cache.ACache;
import com.aube.BaseActivity;
import com.aube.R;
import com.aube.control.player.AbstractVideoHelper;
import com.aube.utils.ServerSwitchUtil;
import com.aube.video.module.ModuleItem;
import com.aube.video.module.VideoThemeListModule;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.SharedPrefUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by huyaonan on 16/9/7.
 */
public class PreferenceActivity extends BaseActivity {
    private static final String TAG = "PreferenceActivity";

    private View mMenuCache, mMenuCC, mMenuProxy, mMenuExo, mMenuServer, mMenuVideoBalance, mMenuVideoTheme;
    private ToggleButton mCCToggle, mProxyToggle, mExoToggle, mServerToggle, mVideoBalanceToggle;
    private Spinner mVideoThemeSpinner;

    private List<String> mVideoThemeList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_preference);

        mMenuCache = findViewById(R.id.menu_clear_cache);
        mMenuCC = findViewById(R.id.menu_toggle_cc);
        mMenuProxy = findViewById(R.id.menu_toggle_proxy);
        mMenuExo = findViewById(R.id.menu_toggle_exo);
        mMenuVideoBalance = findViewById(R.id.menu_toggle_video_balance);
        mMenuServer = findViewById(R.id.menu_switch_server);
        mMenuVideoTheme = findViewById(R.id.menu_toggle_videotheme);

        mCCToggle = (ToggleButton) findViewById(R.id.menu_toggle_cc_toggle);
        mProxyToggle = (ToggleButton) findViewById(R.id.menu_toggle_proxy_toggle);
        mExoToggle = (ToggleButton) findViewById(R.id.menu_toggle_exo_toggle);
        mVideoBalanceToggle = (ToggleButton) findViewById(R.id.menu_toggle_video_balance_toggle);
        mServerToggle = (ToggleButton) findViewById(R.id.menu_switch_server_toggle);
        mVideoThemeSpinner = (Spinner) findViewById(R.id.menu_videotheme_spinner);

        mVideoThemeList.add(0, "Disable");
        fillVideoThemeSpinner();

        mMenuCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPrefUtil.getInstance(PreferenceActivity.this).clear();
                UserUtil.clearData(PreferenceActivity.this);
                Utils.showToast(PreferenceActivity.this, "数据已清空!");
            }
        });

        mCCToggle.setChecked(!AbstractVideoHelper.DO_NOT_USE_CC);
        mProxyToggle.setChecked(AbstractVideoHelper.ENABLE_SOCKET_PROXY);
        mExoToggle.setChecked(AbstractVideoHelper.ENABLE_EXOPLAYER_MODE);
        mVideoBalanceToggle.setChecked(AbstractVideoHelper.ENABLE_VIDEO_BALANCE);

        String path = SharedPrefUtil.getInstance(this).getString(SharedPrefUtil.API_PATH);
        int which = whichServer(path);
        if(which == 0) {
            mServerToggle.setChecked(false);
        } else {
            mServerToggle.setChecked(true);
        }
        mMenuServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mServerToggle.toggle();
                ServerSwitchUtil.clearPluginFiles(PreferenceActivity.this);

                ACache.get(PreferenceActivity.this).clear();
                UserUtil.logout(PreferenceActivity.this);
            }
        });

        mMenuCC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCCToggle.toggle();
            }
        });
        mMenuProxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProxyToggle.toggle();
            }
        });
        mMenuExo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mExoToggle.toggle();
            }
        });
        mMenuVideoBalance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVideoBalanceToggle.toggle();
            }
        });

        mMenuVideoTheme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        mCCToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AbstractVideoHelper.DO_NOT_USE_CC = !isChecked;
            }
        });
        mProxyToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AbstractVideoHelper.ENABLE_SOCKET_PROXY = isChecked;
            }
        });
        mExoToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AbstractVideoHelper.ENABLE_EXOPLAYER_MODE = isChecked;
            }
        });
        mVideoBalanceToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                AbstractVideoHelper.ENABLE_VIDEO_BALANCE = isChecked;
            }
        });
        mServerToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String content = whichServer(isChecked);
                SharedPrefUtil.getInstance(PreferenceActivity.this).putString(SharedPrefUtil.API_PATH, content);

                OpenApi.setRouter(content);
            }
        });
        mVideoThemeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                SharedPrefUtil.getInstance(PreferenceActivity.this).putString(SharedPrefUtil.VIDEO_THEME, mVideoThemeList.get(pos));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }

    private int whichServer(String path) {
        if(StringUtils.isBlank(path))
            return 0;
        if(OpenApi.ROUTER_ONLINE.equalsIgnoreCase(path))
            return 0;
        else if(OpenApi.ROUTER_TEST.equalsIgnoreCase(path))
            return 1;
        else
            return 0;
    }

    private String whichServer(boolean checked) {
        return checked ? OpenApi.ROUTER_TEST : OpenApi.ROUTER_ONLINE;
    }

    private void fillVideoThemeSpinner() {
        HashMap<String, String> params = new HashMap<>();
        params.put("method", OpenApi.VIDEO_THEME_LIST_TEST);
        BFJSONRequest request = new BFJSONRequest(VideoThemeListModule.class, params, new Response.Listener<VideoThemeListModule>() {
            @Override
            public void onResponse(VideoThemeListModule response) {
                if (response != null && response.success() && response.data != null) {
                    for(ModuleItem moduleItem : response.data) {
                        if(moduleItem.themeCode != null && StringUtils.isNotBlank(moduleItem.themeCode)) {
                            mVideoThemeList.add(moduleItem.themeCode);
                        }
                    }

                    fillVideoThemeSpinnerInternal();
                    Utils.Log(TAG, "[getTestVideoTheme.onResponse] Failed. Try loading selected theme.");
                } else {
                    Utils.Log(TAG, "[getTestVideoTheme.onResponse] Failed: response error. Try loading selected theme.");
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.Log(TAG, "[getTestVideoTheme.onErrorResponse] Failed.Try loading selected theme.");
            }

            @Override
            public void onStart() {
            }
        });
        HttpRequestLoader.getInstance(this).startHttpLoader(request);
    }

    private void fillVideoThemeSpinnerInternal() {
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(PreferenceActivity.this, android.R.layout.simple_spinner_item, mVideoThemeList);
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mVideoThemeSpinner.setAdapter(spinnerArrayAdapter);
        mVideoThemeSpinner.setSelection(0);

        String videoTheme = SharedPrefUtil.getInstance(this).getString(SharedPrefUtil.VIDEO_THEME);
        if(videoTheme != null && StringUtils.isNotBlank(videoTheme)) {
            for(int i = 0; i < mVideoThemeList.size(); i++) {
                if(mVideoThemeList.get(i).equalsIgnoreCase(videoTheme)) {
                    mVideoThemeSpinner.setSelection(i);
                }
            }
        }
    }

}
